/**
 * ImageUtil.java [V 1.0.0]
 * classes :com.xlab.basecomm.util.ImageUtil
 * allow.xuweibin Create in  2014年11月15日 上午10:40:17
 */
package com.dragon.utilslibrary.tools;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Environment;
import android.util.Log;
import android.view.View;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 图片操作工具类
 */
public class ImageUtils {
    /**
     * 压缩图片
     *
     * @param image 被压缩的图片
     * @return 返回压缩后的图片
     */
    public static Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        if (baos.toByteArray().length / 1024 > 1024) {// 判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
            LogUtils.d("compressImage ====", "-----进行压缩-----------------------");
            baos.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, 50, baos);// 这里压缩50%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        // 高和宽我们设置为
        int hh = 100;
        int ww = 100;
        // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = w / ww;
        if (be <= 1) {
            be = 1;
        } else if (be > 1 && be <= 3) {
            be = 2;
        } else if (be > 3 && be < 8) {
            be = 4;
        } else {
            be = 8;
        }
        newOpts.inSampleSize = be;// 设置缩放比例
        // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        isBm = new ByteArrayInputStream(baos.toByteArray());
        bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        try {
            baos.close();
            isBm.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return getRoundedCornerBitmap(bitmap);
    }

    /**
     * 压缩图片
     *
     * @param image 被压缩的图片
     * @return 返回压缩后的图片
     */
    public static Bitmap compressHeadImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        if (baos.toByteArray().length / 1024 > 1024) {// 判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
            baos.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, 50, baos);// 这里压缩50%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        // 高和宽我们设置为
        int hh = 100;
        int ww = 100;
        // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = w / ww;
        if (be <= 1) {
            be = 1;
        } else if (be > 1 && be <= 3) {
            be = 2;
        } else if (be > 3 && be < 8) {
            be = 4;
        } else {
            be = 8;
        }
        newOpts.inSampleSize = be;// 设置缩放比例
        // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        isBm = new ByteArrayInputStream(baos.toByteArray());
        bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        try {
            baos.close();
            isBm.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return getRoundedCornerBitmap(bitmap);
    }

    /**
     * 质量压缩方法
     *
     * @param image
     * @return
     */
    private static Bitmap compressImg(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        int options = 100;
        while (baos.toByteArray().length / 1024 > 200) {
            baos.reset();
            image.compress(Bitmap.CompressFormat.JPEG, 50, baos);
            options -= 10;
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
        return bitmap;
    }

    /**
     * 图片按比例大小压缩方法（根据路径获取图片并压缩）
     *
     * @param srcPath
     * @return
     */
    private static Bitmap getImage(String srcPath) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// 此时返回bm为空

        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        // 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        float hh = 400f;// 这里设置高度为800f
        float ww = 240f;// 这里设置宽度为480f
        // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;// be=1表示不缩放
        if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;// 设置缩放比例
        // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        return compressImg(bitmap);// 压缩好比例大小后再进行质量压缩
    }

    /**
     * 转成圆形图片
     *
     * @param bitmap
     * @return
     */
    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = bitmap.getWidth() / 2;

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return output;
    }


    /**
     * 转换图片成圆形
     *
     * @param bitmapStr 传入Bitmap对象
     * @return
     */
    public static Bitmap toRoundBitmap(String bitmapStr) {
        if (bitmapStr == null || "".equals(bitmapStr)) {
            return null;
        }
        Bitmap bitmap = BitmapFactory.decodeFile(bitmapStr);
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float roundPx;// The radius of the picture
        float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
        if (width <= height) {
            roundPx = width / 2;

            // Define the coordinate of the 4 points of the rectangle
            top = 0;
            bottom = width;
            left = 0;
            right = width;

            height = width;

            // Define the coordinate of the 4 points of the rectangle
            dst_left = 0;
            dst_top = 0;
            dst_right = width;
            dst_bottom = width;
        } else {
            roundPx = height / 2;
            float clip = (width - height) / 2;

            left = clip;
            right = width - clip;
            top = 0;
            bottom = height;

            width = height;

            dst_left = 0;
            dst_top = 0;
            dst_right = height;
            dst_bottom = height;
        }

        Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect src = new Rect((int) left, (int) top, (int) right,
                (int) bottom);
        final Rect dst = new Rect((int) dst_left, (int) dst_top,
                (int) dst_right, (int) dst_bottom);
        final RectF rectF = new RectF(dst);

        paint.setAntiAlias(true);

        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, src, dst, paint);

        return output;
    }

    /*
     * 获取view的截图
     */
    public static Bitmap getCutView(Activity activity, int a, int b) {
        // View是屏幕的截图
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap b1 = view.getDrawingCache();
        // 获取屏幕长和高
        int width = activity.getWindowManager().getDefaultDisplay().getWidth();
        Rect rect = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        int statusBarHeight = rect.top;
        LogUtils.e("TAG", " a = " + a + " statuBarHeight = " + statusBarHeight + " b = " + b + " width = " + width + " b1.w = " + b1.getWidth()
                + " b1.h = " + b1.getHeight());
        Bitmap bmp = Bitmap.createBitmap(b1, 0, a + statusBarHeight, width, b);
        view.setDrawingCacheEnabled(false);
        view.destroyDrawingCache();
        return bmp;
    }

    /*
     * 几张Bitmap图片生成Bitmap
     */
    public static Bitmap mosaicImage(Bitmap mapbmp, Bitmap... bmps) {
        Bitmap bitmap = null;
        int bitmapWidth = 0;
        int bitmapHeight = mapbmp.getHeight();
        bitmapWidth = mapbmp.getWidth();
        for (Bitmap bmp : bmps) {
            bitmapHeight += bmp.getHeight();
        }
        bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        int height = 0;
        canvas.drawBitmap(mapbmp, 0, height, null);
        height = mapbmp.getHeight();
        for (Bitmap bmp : bmps) {
            canvas.drawBitmap(bmp, 0, height, null);
            height += bmp.getHeight();
        }
        canvas.save();// 保存
        canvas.restore();// 存储
        return bitmap;
    }

    /**
     * 两张Bitmap图片生成Bitmap把上图贴在下图
     */
    public static Bitmap getNewImage(Bitmap mapbmp, Bitmap bmp) {
        Bitmap bitmap = null;
        int bitmapWidth = 0;
        int bitmapHeight = mapbmp.getHeight();
        bitmapWidth = mapbmp.getWidth();
        bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        int height = 0;
        canvas.drawBitmap(mapbmp, 0, height, null);
        height = mapbmp.getHeight();
        canvas.drawBitmap(bmp, 0, height - bmp.getHeight(), null);
//        canvas.save(Canvas.ALL_SAVE_FLAG);// 保存
        canvas.save();// 保存
        canvas.restore();// 存储
        return bitmap;
    }

    /**
     * 下载头像
     *
     * @param imageUri
     * @return
     */
    public static Bitmap getbitmap(String imageUri) {
        // 显示网络上的图片
        Bitmap bitmap = null;
        try {
            URL myFileUrl = new URL(imageUri);
            HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }

    /**
     * 获取SDCard的目录路径功能
     *
     * @return
     */
    public static String getSDCardPath() {
        File sdcardDir = null;
        // 判断SDCard是否存在
        boolean sdcardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if (sdcardExist) {
            sdcardDir = Environment.getExternalStorageDirectory();
        }
        return sdcardDir.toString();
    }

    public static String saveBitmapToSD(Bitmap Bmp) {
        // 图片存储路径
        String SavePath = getSDCardPath() + "/ScreenImages";
        String filePath = SavePath + "/Screen.png";
        String fileCopyPath = "";
        // 保存Bitmap
        try {
            File path = new File(SavePath);
            // 文件
            File file = new File(filePath);
            if (!path.exists()) {
                path.mkdirs();
            }
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();

            FileOutputStream fos = null;
            fos = new FileOutputStream(file);
            if (null != fos) {
                Bmp.compress(Bitmap.CompressFormat.PNG, 90, fos);
                fos.flush();
                fos.close();
                fileCopyPath = filePath;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileCopyPath;
    }

    public static void saveImgToDisk(File file, Bitmap bitmap) {
        if (file == null) {
            return;
        }
        if (file.exists()) {
            file.delete();
        }

        try {
            file.createNewFile();
            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            String path = file.getPath();
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String saveBitmapToPath(String baseDir, String filename, Bitmap bit) {
        String filePath = baseDir + filename;
        File dir = new File(baseDir);
        if (!dir.exists()) {
            dir.mkdir();
        }

        File f = new File(filePath);
        try {
            f.createNewFile();
            FileOutputStream fOut = null;
            fOut = new FileOutputStream(f);
            bit.compress(Bitmap.CompressFormat.PNG, 100, fOut);
            fOut.flush();
            fOut.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        return filePath;
    }

    /**
     * 压缩并返回上传路径
     *
     * @param path
     * @return
     */
    public static String compressImageUpload(String path) {
        String filename = path.substring(path.lastIndexOf("/") + 1);
        String baseDir = path.substring(0, path.lastIndexOf("/") + 1);
        Log.i("hhhhhhh", baseDir + "=====" + filename);
        Bitmap image = getImage(path);
        return saveBitmapToPath(baseDir, filename, image);
    }

}
